import 'dart:io';

import 'package:edu/constants/app_icons.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/common/dot_radio_button_widget.dart';
import 'package:edu/pages/signin/login/login_page_logic.dart';
import 'package:edu/pages/signin/verify_code_submit/verify_code_submit_page_logic.dart';
import 'package:edu/utils/app_router.dart';
import 'package:edu/utils/app_theme.dart';
import 'package:edu/utils/color_extension.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:tuple/tuple.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  @override
  void initState() {
    super.initState();
    context.read<LoginPageLogic>().init();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: context.read<LoginPageLogic>().resignFucus,
      child: Container(
        color: Theme.of(context).scaffoldBackgroundColor,
        child: SafeArea(child: _buildMainBody(context)),
      ),
    );
  }

  Widget _buildMainBody(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      child: Column(
        children: [
          _buildCloseRow(context),
          const SizedBox(height: 20),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Column(
                children: [
                  _buildTitleRow(context),
                  const SizedBox(height: 20),
                  _buildAccountInputRow(context),
                  const SizedBox(height: 20),
                  _PasswordInputRow(),
                  const SizedBox(height: 20),
                  _MainButtonRow(),
                  const SizedBox(height: 20),
                  _buildSmallButtonRow(context),
                  const Spacer(),
                  _ExtraLoginButtonRow(),
                  const SizedBox(height: 20),
                  _buildFooterRow(context),
                  const SizedBox(height: 20),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 底部
  Widget _buildFooterRow(BuildContext context) {
    final primary = Theme.of(context).colorScheme.primary;
    final normalStyle = Theme.of(
      context,
    ).textTheme.titleSmall?.copyWith(color: Colors.grey);
    final linkStyle = Theme.of(
      context,
    ).textTheme.titleSmall?.copyWith(color: primary);
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 协议勾选框
        Padding(
          padding: const EdgeInsets.only(top: 3.5),
          child: Selector<LoginPageLogic, Tuple2<bool, bool>>(
            selector: (context, logic) =>
                Tuple2(logic.isAgreeDeal, logic.isFetching),
            builder: (context, value, child) {
              final logic = context.read<LoginPageLogic>();
              return DotRadioButtonWidget(
                radius: 7,
                strokeColor: Colors.grey,
                strokeWidth: 1,
                dotColor: primary,
                onChanged: logic.agreeDealChanged,
                value: value.item1,
                enabled: !value.item2,
              );
            },
          ),
        ),
        const SizedBox(width: 5),
        // 协议
        _ProtocolTipText(
          startText: AppStrings.loginFooterText1,
          normalStyle: normalStyle,
          linkStyle: linkStyle,
        ),
      ],
    );
  }

  // 标题
  Widget _buildTitleRow(BuildContext context) {
    return Row(
      children: [
        Selector<LoginPageLogic, Tuple2<String, String?>>(
          selector: (context, logic) => Tuple2(logic.title, logic.subTitle),
          builder: (context, value, child) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  value.item1,
                  style: Theme.of(context).textTheme.titleLarge,
                ),
                const SizedBox(height: 10),
                if (value.item2 != null)
                  Text(
                    value.item2!,
                    style: Theme.of(
                      context,
                    ).textTheme.titleSmall?.copyWith(color: Colors.grey),
                  ),
              ],
            );
          },
        ),
      ],
    );
  }

  // 账号输入框
  Widget _buildAccountInputRow(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child:
              Selector<
                LoginPageLogic,
                Tuple4<bool, TextInputType, String, bool>
              >(
                selector: (context, logic) =>
                    Tuple4<bool, TextInputType, String, bool>(
                      logic.isFetching,
                      logic.keyboardType,
                      logic.inputHitText,
                      logic.accountController.text.isNotEmpty,
                    ),
                builder: (context, value, child) {
                  final logic = context.read<LoginPageLogic>();
                  return TextField(
                    enabled: !value.item1,
                    keyboardType: value.item2,
                    textInputAction: TextInputAction.done,
                    controller: logic.accountController,
                    autofocus: true,
                    focusNode: logic.accountFocusNode,
                    decoration: InputDecoration(
                      contentPadding: const EdgeInsets.symmetric(
                        vertical: 12,
                        horizontal: 12,
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(6.0),
                        borderSide: BorderSide.none,
                      ),
                      fillColor: AppTheme.shared.inputTextFieldBackgroundColor,
                      filled: true,
                      hintText: value.item3,
                      suffixIcon: value.item4
                          ? IconButton(
                              onPressed: logic.clearAccountText,
                              icon: const Icon(Icons.clear),
                            )
                          : null,
                    ),
                  );
                },
              ),
        ),
      ],
    );
  }

  Widget _buildCloseRow(BuildContext context) {
    return Row(
      children: [
        IconButton(
          onPressed: () {
            context.pop();
          },
          icon: const Icon(Icons.close),
        ),
        const Spacer(),
      ],
    );
  }

  // 左侧按钮文本会根据业务逻辑动态变化，右侧则是固定的 "忘记密码" 按钮，整体风格与应用主题保持一致
  Widget _buildSmallButtonRow(BuildContext context) {
    final style = Theme.of(
      context,
    ).textTheme.titleSmall?.copyWith(color: Colors.grey);

    final logic = context.read<LoginPageLogic>();

    return Row(
      children: [
        // 密码登录
        GestureDetector(
          onTap: () {
            logic.switchLoginType();
          },
          child: Selector<LoginPageLogic, String>(
            builder: (context, v, child) {
              return Text(v, style: style);
            },
            selector: (context, logic) => logic.inputTypeTitle,
          ),
        ),
        const Spacer(),
        // 忘记密码
        GestureDetector(
          onTap: () {
            context.pushNamed(
              AppRouter.kForgotPasswordSetting,
              queryParameters: {'prev_route': AppRouter.kLogin},
            );
          },
          child: Text(AppStrings.forgotPassword, style: style),
        ),
      ],
    );
  }
}

// 密码输入框
class _PasswordInputRow extends StatelessWidget {
  const _PasswordInputRow();

  @override
  Widget build(BuildContext context) {
    return Selector<LoginPageLogic, bool>(
      selector: (context, logic) =>
          logic.type == LoginInputType.accountPassword,
      builder: (context, v, child) {
        if (v) {
          return Column(
            children: [
              const SizedBox(height: 10),
              _buildPasswordInputRow(context),
            ],
          );
        } else {
          return const SizedBox.shrink();
        }
      },
    );
  }

  Widget _buildPasswordInputRow(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: Selector<LoginPageLogic, Tuple2<bool, bool>>(
            selector: (context, logic) =>
                Tuple2<bool, bool>(logic.isFetching, logic.obscurePassword),
            builder: (context, v, child) {
              final logic = context.read<LoginPageLogic>();
              return TextField(
                enabled: !v.item1,
                textInputAction: TextInputAction.done,
                controller: logic.passwordController,
                obscureText: v.item2,
                focusNode: logic.passwordFocusNode,
                decoration: InputDecoration(
                  contentPadding: const EdgeInsets.symmetric(
                    vertical: 12,
                    horizontal: 12,
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(6.0),
                    borderSide: BorderSide.none,
                  ),
                  fillColor: AppTheme.shared.inputTextFieldBackgroundColor,
                  filled: true,
                  hintText: AppStrings.passwordHintText,
                  suffixIcon: IconButton(
                    icon: v.item2
                        ? const Icon(
                            Icons.visibility_off,
                            color: Colors.grey,
                            size: 20,
                          )
                        : const Icon(
                            Icons.visibility,
                            color: Colors.grey,
                            size: 20,
                          ),
                    onPressed: logic.switchPasswordVisible,
                  ),
                ),
              );
            },
          ),
        ),
      ],
    );
  }
}

// 登录按钮
class _MainButtonRow extends StatelessWidget {
  const _MainButtonRow();

  @override
  Widget build(BuildContext context) {
    return Row(
      // 登录按钮居中显示
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Expanded(
          child: SizedBox(
            height: 44,
            child: Selector<LoginPageLogic, bool>(
              selector: (context, logic) => logic.mainButtonEnabled,
              builder: (context, v, child) {
                return ElevatedButton(
                  onPressed: v
                      ? () {
                          _mainButtonPressed(context);
                        }
                      : null,
                  style: ButtonStyle(
                    // 圆角按钮
                    shape: WidgetStateProperty.all<RoundedRectangleBorder>(
                      RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                    ),
                  ),
                  child: Selector<LoginPageLogic, String>(
                    selector: (context, logic) => logic.mainButtonText,
                    builder: (context, v, child) {
                      return Text(
                        v,
                        style: Theme.of(context).textTheme.titleLarge,
                      );
                    },
                  ),
                );
              },
            ),
          ),
        ),
      ],
    );
  }

  // 登录按钮点击,提示是否同意协议
  void _showMyDialog(BuildContext context, LoginPageLogic logic) {
    final style = Theme.of(
      context,
    ).textTheme.titleMedium?.copyWith(color: Colors.grey);
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          content: _buildAlertTipRow(context, logic),
          actions: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text(AppStrings.disagree, style: style),
                ),
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    _mainButtonAction(context, logic);
                  },
                  child: Text(AppStrings.agree, style: style),
                ),
              ],
            ),
          ],
        );
      },
    );
  }

  Widget _buildAlertTipRow(BuildContext context, LoginPageLogic logic) {
    final primary = Theme.of(context).colorScheme.primary;
    final normalStyle = Theme.of(
      context,
    ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold);
    final linkStyle = Theme.of(
      context,
    ).textTheme.titleMedium?.copyWith(color: primary);

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _ProtocolTipText(
          startText: AppStrings.alertTipStartText,
          normalStyle: normalStyle,
          linkStyle: linkStyle,
          logic: logic,
        ),
      ],
    );
  }

  // 登录按钮点击事件
  void _mainButtonPressed(BuildContext context) {
    final logic = context.read<LoginPageLogic>();
    logic.resignFucus();
    if (logic.isAgreeDeal) {
      // 登录
      _mainButtonAction(context, logic);
    } else {
      // 协议提示
      _showMyDialog(context, logic);
    }
  }

  // 登录按钮点击事件
  void _mainButtonAction(BuildContext context, LoginPageLogic logic) {
    final goRouter = GoRouter.of(context);
    logic.submit().then((value) {
      if (!value) {
        return;
      }
      // 使用密码登录
      if (logic.type == LoginInputType.accountPassword) {
        // 登录成功
        goRouter.pop();
      } else {
        goRouter.pushNamed(
          AppRouter.kVerifyCodeSubmit,
          queryParameters: {
            'submit_type': VerifyCodeSubmitPageLogic.kLoginVerifyCode,
            'hold_value': logic.accountController.text,
            'prev_route': AppRouter.kMainTab,
          },
        );
      }
    });
  }
}

// 额外的登录方式按钮组
class _ExtraLoginButtonRow extends StatelessWidget {
  const _ExtraLoginButtonRow();

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 微信
        _buildCircleImageLoginButton(context, AppIcons.wechart, () {}),
        // QQ
        _buildCircleImageLoginButton(context, AppIcons.qq, () {}),
        // 微博
        _buildCircleImageLoginButton(context, AppIcons.weibo, () {}),
        // Apple
        if (Platform.isIOS || Platform.isMacOS)
          _buildCircleImageLoginButton(context, AppIcons.apple, () {}),
        // Google
        if (Platform.isAndroid)
          _buildCircleImageLoginButton(context, AppIcons.google, () {}),
      ],
    );
  }

  // 圆形图片按钮
  Widget _buildCircleImageLoginButton(
    BuildContext context,
    String image,
    GestureTapCallback onTap,
  ) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 40,
        height: 40,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Theme.of(context).colorScheme.surface.withValues(alpha: 0.5),
        ),
        child: Center(
          child: ColorFiltered(
            colorFilter: ColorFilter.mode(Colors.grey[600]!, BlendMode.srcIn),
            child: Image.asset(image, width: 25),
          ),
        ),
      ),
    );
  }
}

// 协议提示
class _ProtocolTipText extends StatelessWidget {
  final String startText;
  final TextStyle? normalStyle;
  final TextStyle? linkStyle;
  final LoginPageLogic? logic;
  const _ProtocolTipText({
    required this.startText,
    this.normalStyle,
    this.linkStyle,
    this.logic,
  });

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: RichText(
        text: TextSpan(children: _buildTextSpans(context)),
        maxLines: 5,
        overflow: TextOverflow.ellipsis,
        textAlign: TextAlign.center,
      ),
    );
  }

  List<TextSpan> _buildTextSpans(BuildContext context) {
    final logic = this.logic ?? context.read<LoginPageLogic>();
    final background = Theme.of(context).scaffoldBackgroundColor;
    final bg = background.toHex();
    final fg =
        Theme.of(context).textTheme.titleMedium?.color?.toHex() ??
        background.toHex();
    final tapGesture1 = TapGestureRecognizer()
      ..onTap = () {
        // 跳转协议页面
        if (logic.isFetching) return;
        context.pushNamed(
          AppRouter.kWebViewPage,
          queryParameters: {
            'page': 'userprotocol',
            'title': AppStrings.userProtocol,
            'bg': bg,
            'fg': fg,
          },
        );
      };
    final tapGesture2 = TapGestureRecognizer()
      ..onTap = () {
        // 跳转协议页面
        if (logic.isFetching) return;
        context.pushNamed(
          AppRouter.kWebViewPage,
          queryParameters: {
            'page': 'userprivacy',
            'title': AppStrings.privacyPolicy,
            'bg': bg,
            'fg': fg,
          },
        );
      };
    return [
      TextSpan(text: startText, style: normalStyle),
      TextSpan(
        text: AppStrings.loginFooterText2,
        style: linkStyle,
        recognizer: tapGesture1,
      ),
      TextSpan(text: AppStrings.loginFooterText3, style: normalStyle),
      TextSpan(
        text: AppStrings.loginFooterText4,
        style: linkStyle,
        recognizer: tapGesture2,
      ),
    ];
  }
}
